package org.demo.treeeditor;

import java.awt.event.KeyEvent;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.boxlayout.gui.BoxLayoutEngine;
import org.boxlayout.gui.KeyCustomable;

public class KeyboardManager {

	Map<Integer, Runnable> actions = new HashMap<Integer, Runnable>();
	Boolean editMode = false;
	TextPrompt tp ;
	BoxLayoutEngine ble;
	public void setBoxLayoutEngine(BoxLayoutEngine aBle) {
		ble = aBle;
		aBle.setOnKey(new KeyCustomable() {

			public void onKeyPressed(KeyEvent e) {
				System.out.println("onKeyPressed:" + e.getKeyCode()+" "+e.getKeyText(e.getKeyCode())+" "+e.getKeyChar());
				

				if(editMode){
					if(e.getKeyCode()==0/*back_space*/){
						System.out.println(ble.getRootElement().serializeToText(""));
					}else if(e.getKeyCode()==8/*back_space*/){
						tp.backSpace();
					}else if(e.getKeyCode()==153/*back_space*/){
						tp.hide();
					}else if(e.getKeyCode()==44/*back_space*/){
						tp.type(" ");
					}else if(e.getKeyCode()==32/*space*/){
						tp.save();
						editMode=false;
						
					}else{
						tp.type(""+e.getKeyChar());
					}
				}
				
				if(!editMode){
					Runnable action = actions.get(e.getKeyCode());
					if(action==null){
						System.out.println("no action found for "+e.getKeyCode());
					}else{
						action.run();
					}
				}
			}

			
			public void onKeyReleased(KeyEvent e) {
				System.out.println("onKeyReleased:" + e.getKeyCode()+" "+e.getKeyText(e.getKeyCode())+" "+e.getKeyChar());
				

			}

			
			public void onKeyTyped(KeyEvent e) {
				//System.out.println("onkeyTyped:" + e.getKeyCode()+" "+e.getKeyText(e.getKeyCode())+" "+e.getKeyChar());
			}

		});

	}

	public void setAction(String string, Runnable moveUp) {
		int keycode = stringToKeyCode(string); 
		System.out.println("setting..."+keycode);
		actions.put(keycode, moveUp);
		
	}
	
	public void setAction(Integer keyCode, Runnable moveUp) {
		System.out.println("setting..."+keyCode);
		actions.put(keyCode, moveUp);
		
	}

	public void clearActions(){
		actions.clear();
	}
	
	Integer stringToKeyCode(String string) {
		return (int)string.charAt(0);
	}

	public void setEditMode(Boolean edit) {
		editMode = edit;
	}

	public void setTextPrompt(TextPrompt tp2) {
		this.tp = tp2;		
	}



}
